<?php

namespace app\admin\model;

use think\Model;
use think\Db;

class Buy extends Model
{   


    function getFeature($pro_id,$prochar_id,$lang='zh')
    {
        $featureArr = getDatas('profeature2char',['*'],['pro_id'=>$pro_id,'prochar_id'=>$prochar_id]);
        if(!empty($featureArr)){
            foreach ($featureArr as $k => $v) {
                $feature[$k]['name_id'] = $v['profeature_id'];
                $feature[$k]['name'] = getValue('multi_lang',['mkey'=>'proattr_'.$v['profeature_id'],'lang'=>$lang],'content');
                $feature[$k]['value_id'] = $v['profeature_value_id'];
                $feature[$k]['value'] = getValue('multi_lang',['mkey'=>'proattr_value_'.$v['profeature_value_id'],'lang'=>$lang],'content');
            }
        }else{
            $feature = [];
        }
        return $feature;
    }

    // 获取产品和产品角色信息
    function getProAndProchar($pro_id,$prochar_id,$lang='zh')
    {
        if(!$pro_id) return json_encode(array('status'=>2,'msg'=>lang('missing_product')));
        if(!$prochar_id) return json_encode(array('status'=>2,'msg'=>lang('missing_role_product')));
        // 产品信息
        $join = [
                    ['multi_lang mu','zu.mkey = mu.mkey','LEFT'],
                    ['prodesc d','zu.id = d.pro_id','LEFT'],
                    ['pro_brand b','zu.brand_id = b.id','LEFT'],
                    ['pro_img i','zu.id = i.pro_id','LEFT']
                ];
        $proList = getSearch('pro','zu',['mu.content,d.content prodesc,b.name brand_name,i.img_url'],['zu.id'=>$pro_id,'mu.lang'=>$lang,'d.prodesc_cat_id'=>1,'d.lang'=>$lang],$join,'zu.id desc',[],'i.pro_id');
        // dump($proList);die;
        // $proList = getSearch('pro','zu',['mu.content,d.content prodesc,b.name brand_name,i.img_url'],['zu.id'=>$pro_id,'mu.lang'=>$lang,'d.prodesc_cat_id'=>0,'d.lang'=>$lang],$join,'zu.id desc');
        if(!empty($proList)){
            $proList = $proList[0];
            $proList['id'] = $pro_id;
        } 
        // dump($proList);die;

        // 产品角色信息
        $prochar['model'] = getValue('prochar',['id'=>$prochar_id],'model');
        if($prochar['model']){
            $prochar['id'] = $prochar_id;
            $prochar['feature'] = model('Buy')->getFeature($pro_id,$prochar_id);
        }
        $returnData['proList'] = $proList;
        $returnData['prochar'] = $prochar;
        return $returnData;
    }

    // 获取 产品/产品角色下的介绍类型：产品规格，装箱说明，其他备注
    function getProdesc_cat($pro_id,$prochar_id)
    {
        if(!$pro_id) return json_encode(array('status'=>2,'msg'=>lang('missing_product')));
        if(!$prochar_id) return json_encode(array('status'=>2,'msg'=>lang('missing_role_product')));
        $a = getSearch('multi_lang','zu',['pc.id'],['zu.lang'=>'zh','zu.content'=>'产品规格'],[['prodesc_cat pc','zu.mkey = pc.mkey']],'zu.id desc');
        $b = getSearch('multi_lang','zu',['pc.id'],['zu.lang'=>'zh','zu.content'=>'装箱说明'],[['prodesc_cat pc','zu.mkey = pc.mkey']],'zu.id desc');
        $c = getSearch('multi_lang','zu',['pc.id'],['zu.lang'=>'zh','zu.content'=>'其他备注'],[['prodesc_cat pc','zu.mkey = pc.mkey']],'zu.id desc');

        if(!empty($a)){
            $prodesc_cat[0] = $a[0];$prodesc_cat[0]['name'] = '产品规格';
        } 
        if(!empty($b)){
            $prodesc_cat[1] = $b[0];$prodesc_cat[1]['name'] = '装箱说明'; 
        } 
        if(!empty($c)){
            $prodesc_cat[2] = $c[0];$prodesc_cat[2]['name'] = '其他备注';
        }
        // dump($prodesc_cat);die;
        if(!empty($prodesc_cat)){
            foreach ($prodesc_cat as $k => $v) {
                $prodesc_cat[$k]['content'] = getValue('prodesc',['lang'=>'zh','pro_id'=>$pro_id,'prochar_id'=>$prochar_id,'prodesc_cat_id'=>$v['id']],'content');
            } 
        }else{
            $prodesc_cat = [];
        }
        // dump($prodesc_cat);die;
        return $prodesc_cat;

    }

        // 获取产品角色配件信息
    function getPro_item($pro_id,$prochar_id,$lang='zh')
    {
        $pro_item_join = [
                            ['pro p','zu.pro_id2item = p.id','LEFT'],
                            ['multi_lang mp','p.mkey = mp.mkey','LEFT'],
                            ['pro_brand b','p.brand_id = b.id','LEFT'],
                            ['prochar pc','zu.prochar_id2item = pc.id','LEFT']
                        ];
        $pro_item = getSearch('pro_item','zu',['zu.id','zu.qty','zu.pro_id2item','zu.prochar_id2item','b.name brand_name,pc.model,mp.content'],['zu.pro_id'=>$pro_id,'zu.prochar_id'=>$prochar_id,'mp.lang'=>$lang],$pro_item_join,'zu.id desc');
        if(!empty($pro_item)){
            foreach ($pro_item as $k1 => $v1) {
                $has = hasData('pro_item_type',['pro_id'=>$v1['pro_id2item'],'prochar_id'=>$v1['prochar_id2item']]);
                if($has){
                    $pro_item[$k1]['is_public'] = 1;
                }else{
                    $pro_item[$k1]['is_public'] = 0;
                }
               $pro_item[$k1]['match_ratio'] = 1.02;
            }
        }
        return $pro_item;
    }


        // 根据计划订单Id 获取计划订单详情
    function getBuyPlan($where,$lang)
    {   
        $where['mp.lang'] =$lang;
        $join = [
            ['pro p','zu.pro_id = p.id','LEFT'],
            ['multi_lang mp','p.mkey = mp.mkey','LEFT'],   // 产品名称
            ['pro_brand b','p.brand_id = b.id','LEFT'],
            ['prochar c','zu.prochar_id = c.id','LEFT'],   // 产品角色型号
            ['admin a','zu.buy_id = a.id','LEFT'],         // 采购员
            ['port h','zu.port_id = h.id','LEFT'],        // 交货地址
            ['company cp','zu.company_id = cp.id','LEFT']        // 交货地址
        ];
        // dump($join);die;
        $plan = getSearch('buy_plan','zu',['zu.*,b.name brand_name,c.model,mp.content pro_name,a.nickname,h.name address,cp.name company_name'],$where,$join,'zu.id desc');
        if(!empty($plan)){
            foreach ($plan as $k => $v) {
                $plan[$k]['create_name'] = $v['create_id'] == '' ? '-' : getinfo($v['create_id'], 'admin')['nickname'];//编辑者
                $plan[$k]['create_time'] = $v['create_at'] == '' ? '-' : explode(' ', getTimeDates($v['create_at'],9,$lang))[0];
                // $plan[$k]['company_name'] = $v['company_id'] == '' ? '-' : getValue('company',['id'=>$v['company_id']],'name');
                $plan[$k]['price_sum']=$plan[$k]['price']*$plan[$k]['qty']*$plan[$k]['ctn_qty'];
                $plan[$k]['kgs_sum']=$plan[$k]['ctn_kgs']*$plan[$k]['qty'];
                $plan[$k]['m3_sum']=$plan[$k]['ctn_m3']*$plan[$k]['qty'];
                $plan[$k]['qty_sum']=$plan[$k]['ctn_qty']*$plan[$k]['qty'];
                if($plan[$k]['prochar_id'] == 0){
                    $plan[$k]['img_url'] = getValue('pro_img',['pro_id'=>$plan[$k]['pro_id'],'width'=>1000],'img_url');
                    if($plan[$k]['img_url'] != '/static/Admin/img/nt_logo.png') $plan[$k]['img_url'] = getValue('pro_img',['pro_id'=>$plan[$k]['pro_id'],'width'=>48],'img_url');
                }else{
                    $plan[$k]['img_url'] = getValue('pro_img',['pro_id'=>$plan[$k]['pro_id'],'prochar_id'=>$plan[$k]['prochar_id'],'width'=>48],'img_url');
                }
            }
        }
        return $plan;
    }


    function insertPlan2item($data,$buy_plan_id,$type)
    {
        foreach ($data['pro_item'] as $k => $v) {
            // 生成单个配件计划订单
            if($type == 'add'){
                $plan_item = [
                                'pro_id'=>$v['pro_id2item'],
                                'prochar_id'=>$v['prochar_id2item'],
                                'qty'=>$v['qty'],
                                'is_item'=>1,
                                'delivery_at'=> (10*24*60*60+time())
                            ];
                $buy_plan2item_id = insertData('buy_plan',$plan_item);

                $buy_plan2item['buy_plan_id'] = $buy_plan_id;
                $buy_plan2item['pro_item_id'] = $v['id'];
                $buy_plan2item['plan_item_qty'] = $v['qty'];
                $buy_plan2item['difference'] = $v['qty'] - $data['data']['qty']*$v['match_ratio'];
                $buy_plan2item['match_ratio'] = $v['match_ratio'];
                $buy_plan2item['buy_plan_id2item'] = $buy_plan2item_id;
                $buy_plan_iteminsert = insertData('buy_plan2item',$buy_plan2item);
            }else{
                $id = isset($v['buy_plan_id2item']) ? $v['buy_plan_id2item'] : $v['buy_plan_item_id'];
                $buy_plan2item_id = updateData('buy_plan',['id'=>$id],['qty'=>($data['data']['qty']*$v['match_ratio'])]);
                $buy_plan_iteminsert = updateData('buy_plan2item',['id'=>$v['id']],['plan_item_qty'=>($data['data']['qty']*$v['match_ratio']),'difference'=>0]);
            }
            
        }
        if($buy_plan2item_id >= 0 && $buy_plan_iteminsert >= 0){
            return 200;  
        }else{
            return 500;
        } 
        
    }


    // 整理订单计划装箱规格数据
    function getOrganizNorm($data)
    {
        $data = [
                    'ctn_size'=>$data['ctn_size'],
                    'ctn_kgs'=>$data['ctn_kgs'],
                    'ctn_m3'=>$data['ctn_m3'],
                    'qty'=>$data['ctn_qty'],
                    'price_sum'=>$data['price']*$data['qty']*$data['ctn_qty'],
                    'kgs_sum'=>$data['ctn_kgs']*$data['qty'],
                    'm3_sum'=>$data['ctn_m3']*$data['qty'],
                    'qty_sum'=>$data['ctn_qty']*$data['qty'],
                ];
        return $data;
    }


    function getBuyPo($where=[],$lang,$field=[],$whereOr=[],$limit='')
    {
        if(!empty($field)){
            $field_[0] = $field[0]. ',c.name company_name,p.name port_name,l.name linkname,lm.content linkman_method';
        }else{
            $field_ = 'zu.*,c.name company_name,p.name port_name,l.name linkname,lm.content linkman_method';
        }
        $join = [
                    ['company c','zu.company_id = c.id','LEFT'],
                    ['port p','zu.port_id = p.id','LEFT'],        // 交货地址
                    ['linkman l','l.id = zu.linkman_id','LEFT'],
                    ['linkman_method lm','l.id = lm.linkman_id','LEFT']
                ];
        // $where['lm.coattr_id'] = 176;
        $data = getSearch('buy_po','zu',$field_,$where,$join,'zu.id desc',$whereOr,'lm.linkman_id',$limit);
        // dump($field_);die;
        if(!empty($data)){
            foreach ($data as $k => $v) {
                $buy_plan = model('Buy')->getBuyPlan(['zu.po_id'=>$v['id']],$lang);
                $data[$k]['delivery_day'] = explode(' ', getTimeDates($v['delivery_day'],9,$lang))[0];
                if(empty($field)){
                    $data[$k]['paid'] = $v['paid_sum'] > 0 ? $v['paid_sum'] : '-';
                    $data[$k]['sign'] = $v['sign_day'] > 0 ? 'O' : '-';
                    $data[$k]['receipt'] = $v['receipt_day'] > 0 ? 'O' : '-';
                    $data[$k]['create_name'] = $v['create_id'] == '' ? '-' : getinfo($v['create_id'], 'admin')['nickname'];//编辑者
                    $data[$k]['create_time'] = $v['create_at'] == '' ? '-' : explode(' ', getTimeDates($v['create_at'],9,$lang))[0];
                    if(!empty($buy_plan)){
                        $data[$k]['buy_plan'] = $buy_plan;
                        $data[$k]['plan_sum'] = count($buy_plan);
                    }else{
                        $data[$k]['buy_plan'] = [];
                    }
                }
                
            }
        }
        return $data;
    }

    // 合同删除
    function requestDel()
    {
        if(!isset($this->data['id'])) return array('status'=>2,'msg'=>'请选择被删除的数据');
        $res = updateData('buy_po',['id'=>$this->data['id']],['status'=>2]);
        if($res){
            return array('status'=>1,'msg'=>lang('deleted_successfully'));
        }else{
            return array('status'=>0,'msg'=>lang('failed_to_delete'));
        }
    }

    // 编辑合同（新增计划订单，编辑计划订单，移除计划订单）
    function updatePo($po_id,$user_id)
    {
        // 合同详情
        $poInfo = getDatas('buy_po',['*'],['id'=>$po_id]);
        if(!empty($poInfo)){
            // 获取编辑后当前合同得采购订单费用合计
            $planInfo = getDatas('buy_plan',['*'],['po_id'=>$po_id]);
            if(!empty($planInfo)){
                $plan_amount = 0;
                $qty_sum = 0;
                $m3_sum = 0;
                $kgs_sum = 0;
                foreach ($planInfo as $k => $v) {
                    $plan_amount += $v['price']*$v['qty']*$v['ctn_qty'];
                    $qty_sum += $v['qty']*$v['ctn_qty'];
                    $m3_sum += $v['qty']*$v['ctn_m3'];
                    $kgs_sum += $v['qty']*$v['ctn_kgs'];
                    $plan_ids[] = $v['id'];
                }
            }
            // 判断是否已签约，已签约在buy_po_pay追加一组数据，未签约则改变当前合同的百分比金额
            if($poInfo[0]['sign_day']){
                // 因为编辑了合同中得计划订单，因此会影响当前合同得付款安排（百分比不正常），所以需要把每条付款安排得记录的百分比值去掉，只留每个记录的金额数
                $res2 = updateData('buy_po_pay',['po_id'=>$po_id],['percent'=>0]);   
                // 添加一组尾款编辑数据
                $res3 = insertData('buy_po_pay',['pay_day'=>$poInfo[0]['delivery_day'],'amount'=>($plan_amount-$poInfo[0]['price_sum']),'po_id'=>$po_id]);  
            }else{
                $updateData = getDatas('buy_po_pay',['*'],['po_id'=>$po_id]);
                if(!empty($updateData)){
                    foreach ($updateData as $k2 => $v2) {
                        $res4 = updateData('buy_po_pay',['id'=>$v2['id']],['amount'=>$plan_amount*($v2['percent']/100)]);
                    }
                }
            }

            // $cost_sum = $poInfo[0]['cost_sum'] - $poInfo[0]['price_sum'] + $plan_amount;
            // // 修改合同总货款
            // $res5 = updateData('buy_po',['id'=>$po_id],['price_sum'=>$plan_amount,'cost_sum'=>$cost_sum,'qty_sum'=>$qty_sum,'m3_sum'=>$m3_sum,'kgs_sum'=>$kgs_sum,'update_at'=>time(),'update_id'=>$user_id]);
        }
    }


    // 获取未付款的合同及合同的付款安排
    // $type = add  or  edit
    function getPaypoarr($data,$type='edit')
    {
        foreach ($data as $k => $v) {
            if($type=="add"){
               $where = ['po_id'=>$v['id'],'finish_day'=>0];
            }else{
               $where = ['po_id'=>$v['id']];
            }
            $data[$k]['paypoarr'] = getDatas('buy_po_pay',['*'],$where);
            // 付款安排的未付总金额
            $payPoArrAmount_sum = 0;
            $payPoArrPaid_sum = 0;
            if(!empty($data[$k]['paypoarr'])){
                foreach ($data[$k]['paypoarr'] as $k1 => $v1) {
                    $data[$k]['paypoarr'][$k1]['pay_day'] = explode(' ', getTimeDates($v1['pay_day'],9,is_lang()))[0];
                    if($type == 'add') $data[$k]['paypoarr'][$k1]['amount'] = $v1['amount'] - $v1['paid'];
                    $payPoArrAmount_sum += ($v1['amount'] - $v1['paid']);
                    $payPoArrPaid_sum += $v1['paid'];

                }
            }
            // 根据付款安排获取总额，判断是否有其他代付，总货款+其他应付款-已付-付款安排的未付
            if($type == 'add'){
                if($data[$k]['price_sum']+$data[$k]['cost_sum']-$data[$k]['paid_sum']-$payPoArrAmount_sum > 0){
                    $data[$k]['cost_list']['po_id']   = $v['id'];
                    $data[$k]['cost_list']['amount']  = $data[$k]['price_sum']+$data[$k]['cost_sum']-$data[$k]['paid_sum']-$payPoArrAmount_sum;
                    $data[$k]['cost_list']['paid']    = $data[$k]['paid_sum']-$payPoArrPaid_sum;
                    $data[$k]['cost_list']['pay_day'] = $v['delivery_day'];
                }else{
                    $data[$k]['cost_list'] = [];
                }
            }else{
                $data[$k]['cost_list']['po_id']   = $v['id'];
                $data[$k]['cost_list']['amount']  = $data[$k]['cost_sum'];
                $data[$k]['cost_list']['paid']    = $data[$k]['paid_sum']-$payPoArrPaid_sum;
                $data[$k]['cost_list']['pay_day'] = $v['delivery_day'];
            }
        }
        return $data;
    }

    // 批量处理合同状态
    function batchSet($buy_po_ids,$type,$user_id=0)
    {
        switch ($type) {
            case 'sign':
                $updateValue = ['sign_day'=>time()];
                $msg_name = lang('signed');
                break;
            
            case 'receipt':
                $updateValue = ['receipt_day'=>time()];
                $msg_name = lang('received');
                break;
            
            case 'del':
                $updateValue = ['del_at'=>time(),'del_id'=>$user_id,'status'=>2];
                $msg_name = lang('delete');
                break;
        }
        $po_ids = '';
        foreach ($buy_po_ids as $k=> $v) {
            $res = updateData('buy_po',['id'=>$v],$updateValue);
            $po_ids .= $v.',';
        }
        rtrim($po_ids,',');
        if($res) return array('status'=>1,'msg'=>'合同编号：'.$po_ids.' '.$msg_name.' '.lang('successfully'));
        return array('status'=>0,'msg'=>'合同编号：'.$po_ids.' '.$msg_name.' '.lang('failed'));
    }

    // 获取采购合同详情
    function geyBuyPoInfo($plan_ids,$po_id,$request){
        // dump($plan_ids);die;
        foreach ($plan_ids as $k => $v) {
            $plan[$k] = model('Buy')->getBuyPlan(['zu.id'=>$v],is_lang())[0];
            $plan[$k]['delivery_time'] = explode(' ',getTimeDates($plan[$k]['delivery_at'],9,is_lang()))[0];

            $where['pro_id'] = $plan[$k]['pro_id'] == 0 ? 0: $plan[$k]['pro_id'];
            $plan[$k]['img_url'] = getValue('pro_img',['pro_id'=>$plan[$k]['pro_id'],'width'=>1000],'img_url');
            // 判断是否系统图，非系统图则取最小的。
            if($plan[$k]['img_url'] != '/static/Admin/img/nt_logo.png'){
                $where['prochar_id'] = $plan[$k]['prochar_id'] == 0 ? 0: $plan[$k]['prochar_id'];
                $where['width'] = 48;
                $plan[$k]['img_url'] = Db::name('pro_img')->where($where)->group('pro_id')->value('img_url');
            } 

            if(!$plan[$k]['img_url']) $where['prochar_id'] = 0;
            $plan[$k]['img_url'] = Db::name('pro_img')->where($where)->group('pro_id')->value('img_url');
            $plan[$k]['company_name'] = $plan[$k]['company_id'] == 0 ? '-' : getValue('company',['id'=>$plan[$k]['company_id']],'name');
            // 获取产品/产品角色下的介绍类型 内容
            $plan[$k]['prodesc_cat'] = getSearch('buy_plan_remarks','zu',['zu.id buy_plan_remarks_id,zu.prodesc_cat_id id,zu.content,mc.content name'],['zu.buy_plan_id'=>$plan[$k]['id'],'mc.lang'=>is_lang()],[['prodesc_cat pc','zu.prodesc_cat_id = pc.id'],['multi_lang mc','pc.mkey = mc.mkey']],'zu.id asc');
        }
        
        // 交货地址
        $returnData['port'] = getDatas('port',['id,name'],'1=1','id desc');
        
        // 全部公司信息
         $returnData['company'] = $this->searchCompany();

        // 合同条款
        if($request == 'add'){
            $returnData['terms'] = model('Buy')->organizTerms();
        }else{
            // return 123;
            $terms = getDatas('buy_po_terms',['*'],['po_id'=>$po_id],['id desc']);
            if(!empty($terms)){
                foreach ($terms as $k1 => $v1) {
                    $returnData['terms'][$v1['type']]['id'] = $v1['id'];
                    $returnData['terms'][$v1['type']]['content'] = $v1['content'];
                }
            }
            $returnData['buy_po'] = getDatas('buy_po',['*'],['id'=>$po_id])[0];
            // 金额千分位逗号。
            // $returnData['buy_po']['paid_sum'] = number_format($returnData['buy_po']['paid_sum'],2);
            // $returnData['buy_po']['cost_sum'] = number_format($returnData['buy_po']['cost_sum'],2);
            // $returnData['buy_po']['price_sum'] = number_format($returnData['buy_po']['price_sum'],2);
            $returnData['buy_po']['delivery_day'] = explode(' ',getTimeDates($returnData['buy_po']['delivery_day'],9,is_lang()))[0];
            $res = $this->getCompanyLinkmans($returnData['buy_po']['company_id']);
            if(!empty($res['linkman'])){
                $returnData['linkman'] = $res['linkman'];
                $returnData['bank'] = $res['bank'];
                $returnData['country_id'] = $res['country_id'];
            }
            $returnData['paypoarr'] = getDatas('buy_po_pay',['*'],['po_id'=>$po_id],'id asc');
            if(!empty($returnData['paypoarr'])){
                foreach ($returnData['paypoarr'] as $key => $value) {
                    $returnData['paypoarr'][$key]['pay_day'] =  explode(' ',getTimeDates($value['pay_day'],9,is_lang()))[0];
                    $returnData['paypoarr'][$key]['percent'] = $returnData['paypoarr'][$key]['percent'] > 0 ? $returnData['paypoarr'][$key]['percent'] : '-';
                }
            }
            // 获取合同其他费用
            $returnData['cost_list'] = getDatas('buy_po_cost',['*'],['po_id'=>$po_id]);
            $returnData['buy_po']['replace_sum'] = 0;
            if(!empty($returnData['cost_list'])){
                foreach ($returnData['cost_list'] as $k2 => $v2) {
                    $returnData['cost_list'][$k2]['apportion'] = $v2['apportion'] == 0 ? false : true;
                    $returnData['cost_list'][$k2]['is_replace_pay'] = $v2['is_replace_pay'] == 0 ? false : true;
                    if ($v2['is_replace_pay'] == 1) {
                        $returnData['buy_po']['replace_sum'] += $v2['amount'];
                    }
                }
            }

            // 合同编辑日志
            $buy_po_logs = getDatas('buy_po_logs',['*'],['po_id'=>$po_id]);
            if(!empty($buy_po_logs)){
                foreach ($buy_po_logs as $k => $v) {
                    $buy_po_logs[$k]['happen_at'] = explode(' ',getTimeDates($v['happen_at'],9,is_lang()))[0];
                    $buy_po_logs[$k]['admin_name'] = $v['admin_id'] == '' ? '-' : getinfo($v['admin_id'], 'admin')['nickname'];//编辑者
                }
            }
            $join = [
                ['buy_po_pack_remark pr','zu.id = pr.po_pack_id','LEFT'],
                ['prochar pc','zu.prochar_id = pc.id','LEFT'],
                ['pro p','zu.pro_id = p.id','left'],
                ['multi_lang mp','p.mkey = mp.mkey','LEFT'],
                ['pro_brand b','p.brand_id = b.id','LEFT'],
            ];
            // 合同装箱信息
            $returnData['packing'] = getSearch('buy_po_pack','zu',['zu.ctn_qty num,zu.ctn_m3 volume,zu.ctn_kgs witch,zu.ctn_size size,zu.qty boxnum,zu.pro_id,zu.prochar_id,pr.content note,pc.model,mp.content pro_name,b.name brand_name'],['zu.po_id'=>$po_id,'mp.lang'=>is_lang()],$join,'zu.id asc');
            // dump($returnData['packing']);die;
                if(!empty($returnData['packing'])){
                    $result = getDatas('buy_po_pack',['ctn_qty num,ctn_m3 volume,ctn_kgs witch,ctn_size size,qty boxnum,pro_id,prochar_id'],['po_id'=>$po_id,'pro_id'=>0,'prochar_id'=>0]);
                    if(!empty($result)){
                        foreach ($result as $key => $value) {
                            $returnData['packing'][] = $value;
                        }
                    }
                }
            $returnData['buy_po_logs'] = $buy_po_logs;
        }
        $returnData['plan'] = $plan;
        return $returnData;
    }

    // 搜索公司信息
    public function searchCompany($searchCompany=0)
    {
        if($searchCompany){
            $company = getDatas('company',['id,name'],['name'=>['like','%'.$searchCompany.'%']],'id desc');
        }else{
            $company = getDatas('company',['id,name'],'1=1','id desc');
        }
        return $company;
    }


    // 整理合同条款
    function organizTerms(){
        $termsList = getDatas('buy_terms',['*'],'1=1','drank asc');
        if(!empty($termsList)){
            $returnData['general_terms']['id'] = 0;
            $returnData['general_terms']['content'] = '';
            $returnData['delivery_terms']['id'] = 0;
            $returnData['delivery_terms']['content'] = '';
            $returnData['payment_terms']['id'] = 0;
            $returnData['payment_terms']['content'] = '';
            $returnData['after_sales_terms']['id'] = 0;
            $returnData['after_sales_terms']['content'] = '';
            foreach ($termsList as $k => $v) {
                switch ($v['type']) {
                    case 'general_terms':  // 常规条款
                        $returnData['general_terms']['content'] .= '- '.$v['content']."\n";
                        break;
                    case 'delivery_terms':   // 送货条款
                        $returnData['delivery_terms']['content'] .= '- '.$v['content']."\n";
                        break;
                    case 'payment_terms':     // 付款条款
                        $returnData['payment_terms']['content'] .= '- '.$v['content']."\n";
                        break;
                    case 'after_sales_terms'://售后条款
                        $returnData['after_sales_terms']['content'] .= '- '.$v['content']."\n";
                        break;
                }
            }
            return $returnData;
        }else{
            return $returnData = [];
        }
    }

    
    function getCompanyLinkmans($id)
    {
        $returnData['linkman'] = getSearch('company','zu',['l.id,l.name,m.content,c.country_id'],['zu.id'=>$id],[['linkman l','zu.id = l.co_id'],['linkman_method m','l.id = m.linkman_id'],['co_profile c','zu.id = c.co_id']],'zu.id asc');

        $returnData['bank'] = getSearch('co_bank','zu',['zu.id,zu.bankname,zu.account_name,zu.account_num,b.name'],['zu.co_id'=>$id],[['banks b','zu.banks_id = b.id']],'zu.id desc');
        $returnData['country_id'] = getValue('co_profile',['co_id'=>$id],'country_id');
        return $returnData;
    }


    // 根据po_id 获取被编辑的字段信息，完善操作记录信息
    function getupdatelogs($data)
    {
        $plan_ids = getDatas('buy_plan',['id'],['po_id'=>$data['po_id']],'id desc');
        $po_id = $data['po_id'];
        $content = '';
        if(!empty($plan_ids)){
            foreach ($plan_ids as $k => $v) {
                $ids[] = $v['id'];
            }
            $res = $this->geyBuyPoInfo($ids,$po_id,'edit');
            if(!empty($res)){

                if(Db::name('buy_plan')->where(['po_id'=>$po_id])->count() != count($data['ids'])) $content .= '编辑了计划订单的数量,';
                $res1 = array_diff($data['data'], $res['buy_po']);
                foreach ($res1 as $key => $value) {
                    switch ($key) {
                        case 'delivery_day':
                            $content .= '编辑了合同的交货日期;';
                            break;
                        case 'port_id':
                            $content .= '编辑了合同的交货地址;';
                            break;
                        case 'linkman_id':
                            $content .= '编辑了合同的联系人;';
                            break;
                        case 'company_id':
                            $content .= '编辑了合同的所属公司;';
                            break;
                        case 'price_sum':
                            $content .= '编辑了合同的总货款;';
                            break;
                        case 'bank_id':
                            $content .= '编辑了合同的银行账号;';
                            break;
                        case 'qty_sum':
                            $content .= '编辑了合同的总数量;';
                            break;
                        case 'cost_sum':
                            $content .= '编辑了合同的其他费用的代收费用;';
                            break;
                    }
                }
                foreach ($data['terms'] as $k3 => $v3) {
                    $res2 = array_diff($v3, $res['terms'][$k3]);
                    if(!empty($res2)){
                        switch ($k3) {
                            case 'normal':
                                $content .= '修改了合同条款的：常规条款内容;';
                                break;
                            case 'enter':
                                $content .= '修改了合同条款的：送货条款内容;';
                                break;
                            case 'pay':
                                $content .= '修改了合同条款的：付款条款内容;';
                                break;
                            case 'after_sale':
                                $content .= '修改了合同条款的：售后条款内容;';
                                break;
                        }
                    }
                }
                if(count($data['paypoarr']) != count($res['paypoarr'])) $content .= '编辑付款安排';
                foreach ($data['paypoarr'] as $k4=> $v4) {
                    if($v4['percent'] != $res['paypoarr'][$k4]['percent']) $content .= '编辑了付款安排的百分比;';
                }
                if(isset($data['cost_list'])){
                    if(count($data['cost_list']) != count($res['cost_list'])) $content .= '编辑了其他费用;';
                    foreach ($data['cost_list'] as $k5=> $v5) {
                        $m = 1;
                        for ($i=count($res['cost_list'])-1; $i >=0 ; $i--) { 
                            if($v5['remarks'] == $res['cost_list'][$i]['remarks']){
                                if((float)$v5['amount'] != $res['cost_list'][$i]['amount']) $content .= '修改了其他费用：'.$v5['remarks'].'的金额;';
                                if($v5['apportion'] == 'false'){
                                    $v5['apportion'] = false;
                                }else{
                                    $v5['apportion'] = true;
                                } 
                                if($v5['apportion'] != $res['cost_list'][$i]['apportion']) $content .= '修改了其他费用：'.$v5['remarks'].'的分摊成本;';
                                if($v5['is_replace_pay'] != $res['cost_list'][$i]['is_replace_pay']) $content .= '修改了其他费用：'.$v5['remarks'].'是否代付;';
                            }else{
                                $m++;
                            }
                        }
                    }
                }
                
            }
            return $content;
        }
    }


    // 执行付款动作 fin_co2buy_id = 流水Id
    function buyPoPayAction($data,$fin_co2buy_id=0)
    {   
        // 获取当前流水ID下的所有合同下的付款安排和其他带上费用的记录
        $fin = getDatas('fin_co2buy_po',['*'],['fin_co2buy_id'=>$fin_co2buy_id]);
        $paypoarr_ids = array_column($fin,'buy_po_payId');
        foreach ($data as $k => $v) {
            // 付款安排
            if (isset($v['paypoarr']) && !empty($v['paypoarr'])) {
                foreach ($v['paypoarr'] as $k1 => $v1) {
                    // 判断单个付款安排的总额 是否等于当前付款额度+当前付款安排的已支付额度
                    $amount = getDatas('buy_po_pay',['*'],['id'=>$v1['id']])[0];
                    // 获取当前付款安排在流水Id下的支付额度
                    $fin_co2buy_paypoarrpaid = getValue('fin_co2buy_po',['buy_po_payId'=>$v1['id'],'fin_co2buy_id'=>$fin_co2buy_id],'amount');
                    if(!$fin_co2buy_paypoarrpaid) $fin_co2buy_paypoarrpaid = 0;
                    $paypoarrUpdate['finish_day'] = 0;
                    if($v1['check'] == "true"){ // 判断是否选中付款

                        if($fin_co2buy_id){ // 判断是否编辑,编辑状态则已付额度需减去流水额度
                            $paypoarrUpdate['paid'] = $amount['paid'] + $v1['price'] - $fin_co2buy_paypoarrpaid;
                            // $paypoarr_paid += $paypoarrUpdate['paid'];
                            if ($amount['amount'] == $amount['paid'] + $v1['price'] - $fin_co2buy_paypoarrpaid) $paypoarrUpdate['finish_day'] = time();
                        }else{
                            $paypoarrUpdate['paid'] = $v1['price'] + $amount['paid'];
                            // $paypoarr_paid += $paypoarrUpdate['paid'];
                            if ($amount['amount'] == $amount['paid'] + $v1['price']) $paypoarrUpdate['finish_day'] = time();
                        }
                        $res = updateData('buy_po_pay', ['id' => $v1['id']], $paypoarrUpdate);
                    }else if(in_array($v1['id'], $paypoarr_ids) && $v1['check'] == "false"){    // 判断是否存在移除，已经支付过的数据，存在则恢复该数据的已付金额
                        $paypoarrUpdate['paid'] = $amount['paid']-$fin_co2buy_paypoarrpaid;
                        // $paypoarr_paid += $paypoarrUpdate['paid'];
                        if ($amount['amount'] == $amount['paid']-$fin_co2buy_paypoarrpaid) $paypoarrUpdate['finish_day'] = time();
                        $res = updateData('buy_po_pay', ['id' => $v1['id']], $paypoarrUpdate);
                    }

                }
            }
            // 当提交的数据没有支付安排的情况下，获取一遍当前合同Id下，所有支付安排已支付的总和。
            $paypoarr_paid = Db::name('buy_po_pay')->where(['po_id'=>$v['id']])->sum('paid');
            if(!$paypoarr_paid) $paypoarr_paid = 0;
            
            // 其他费用
            $cost_paid = 0;
            // 获取其他流水的合同下的其他费用总和，
            $fin_co2buy_costpaid = getValue('fin_co2buy_po',['fin_co2buy_id'=>['not in',$fin_co2buy_id],'po_id'=>$v['id'],'buy_po_payId'=>0],'amount');
            if(!$fin_co2buy_costpaid) $fin_co2buy_costpaid = 0;
            if (isset($v['cost_list']) && !empty($v['cost_list'])) {
                if($v['cost_list']['check'] == "true"){
                    $cost_paid = $v['cost_list']['price']+$fin_co2buy_costpaid;
                }
                if($v['cost_list']['check'] == "false" && $fin_co2buy_costpaid){
                    $cost_paid = $fin_co2buy_costpaid;
                }
            }else{
                // 当提交的数据没有其他费用的情况下。
                $cost_paid = $fin_co2buy_costpaid; 
            }
            // 根据合同ID 获取付款合计和已付合计
            $poInfo = getDatas('buy_po', ['price_sum,cost_sum,paid_sum'], ['id' => $v['id']]);
            // dump($paypoarr_paid + $cost_paid);die;
            if (!empty($poInfo)) {
                // 判断当前提交的总付款额 是否等于 当前合同未付的总额，相等则该合同 货款两清，字段名finish_day等于当前时间
                if (($paypoarr_paid + $cost_paid) == $poInfo[0]['price_sum'] + $poInfo[0]['cost_sum']) {
                    $buy_po_update[$k]['finish_day'] = time();
                }else{
                    $buy_po_update[$k]['finish_day'] = 0;
                }
                $buy_po_update[$k]['id'] = $v['id'];
                $buy_po_update[$k]['paid_sum'] = $paypoarr_paid + $cost_paid;
            }
        }
        foreach ($buy_po_update as $k2 => $v2) {
            if($v2['paid_sum'] > 0) $res1 = updateData('buy_po',['id'=>$v2['id']],['finish_day'=>$v2['finish_day'],'paid_sum'=>$v2['paid_sum']]);
        }
        return array('status' => 1, 'msg' => '付款成功');
    }


    // 处理合同的装箱单
    function buyPoPack($data,$po_id){
        $res1 = deleteData('buy_po_pack',['po_id'=>$po_id]);
        foreach ($data as $k => $v) {
            $insertData['po_id'] = $po_id;
            $insertData['pro_id'] = isset($v['pro_id']) ? $v['pro_id'] : 0;
            $insertData['prochar_id'] = isset($v['prochar_id']) ? $v['prochar_id'] : 0;
            $insertData['ctn_qty'] = $v['num'];
            $insertData['ctn_kgs'] = $v['witch'];
            $insertData['ctn_m3'] = $v['volume'];
            $insertData['ctn_size'] = $v['size'];
            $insertData['qty'] = $v['boxnum'];
            $insertData['port_id'] = isset($v['port_id']) ? $v['port_id'] : 0;
            $res = insertData('buy_po_pack',$insertData);
            if($res){
                $res1 = insertData('buy_po_pack_remark',['po_pack_id'=>$res,'content'=>$v['note']]);
            }
            if(isset($v['ischeck']) && $v['ischeck'] == "true" && isset($v['id'])){
                $res2 = updateData('buy_plan',['id'=>$v['id']],['ctn_qty' => $v['num'],'ctn_size' => $v['size'],'ctn_m3' => $v['volume'],'ctn_kgs' => $v['witch'] ]);
            }
        }
        if($res){
            return array('status'=>1,'msg'=>'合同装箱单编辑成功');
        }else{
            return array('status'=>0,'msg'=>'合同装箱单编辑失败');
        }
    }

    // 删除合同流水时，恢复该流水得金额
    function delBuyPoFin($fin_co2buy_id)
    {
        $fin = getDatas('fin_co2buy_po',['*'],['fin_co2buy_id'=>$fin_co2buy_id]);
        if(!empty($fin)){
            foreach ($fin as $k => $v) {
                $po_paid_sum = getValue('buy_po',['id'=>$v['po_id']],'paid_sum');
                if($v['buy_po_payId']){
                    $paypoarr_paid = getValue('buy_po_pay',['id'=>$v['buy_po_payId']],'paid');
                    $res = updateData('buy_po_pay',['id'=>$v['buy_po_payId']],['paid'=>($paypoarr_paid-$v['amount']),'finish_day'=>0]);
                    $res1 = updateData('buy_po',['id'=>$v['po_id']],['paid_sum'=>($po_paid_sum - $v['amount']),'finish_day'=>0]); 
                }else{
                    $res1 = updateData('buy_po',['id'=>$v['po_id']],['paid_sum'=>($po_paid_sum - $v['amount']),'finish_day'=>0]);
                }
            }
            if($res1 >= 0){
                return 1;
            }else{
                return 0;
            }
            
        }else{
            return 1;
        }
    }

    //根据合同Id获取装箱清单
    function getPoPack($buy_po,$where,$lang)
    {   
        foreach ($buy_po as $k => $v) {
            $where['po_id']= $v['id'];
            $buy_po_pack = getDatas('buy_po_pack',['*'],$where);
            $buy_po[$k]['CTN'] = 0;
            $buy_po[$k]['KGS'] = 0;
            $buy_po[$k]['CBM'] = 0;
            $buy_po[$k]['CNY'] = 0;
            if(!empty($buy_po_pack)){
                foreach ($buy_po_pack as $k1 => $v1) {
                    $buy_po_pack[$k1]['sum_qty'] = $v1['qty']*$v1['ctn_qty'];
                    $buy_po_pack[$k1]['sum_kgs'] = $v1['qty']*$v1['ctn_qty']*$v1['ctn_kgs'];
                    $buy_po_pack[$k1]['sum_m3']  = $v1['qty']*$v1['ctn_qty']*$v1['ctn_m3'];
                    $wherePlan = [
                                    'po_id'=>$v1['po_id'],
                                    'pro_id'=>$v1['pro_id'],
                                    'prochar_id'=>$v1['prochar_id'] > 0 ? $v1['prochar_id'] : 0
                                ];
                    $price = getValue('buy_plan',$wherePlan,'price');
                    $buy_po_pack[$k1]['price'] = $price;
                    $buy_po_pack[$k1]['sum_price'] = $price*$v1['qty']*$v1['ctn_qty'];


                    $buy_po[$k]['CTN'] += $buy_po_pack[$k1]['sum_qty'];
                    $buy_po[$k]['KGS'] += $buy_po_pack[$k1]['sum_kgs'];
                    $buy_po[$k]['CBM'] += $v1['qty']*$v1['ctn_m3'];
                    $buy_po[$k]['CNY'] += $buy_po_pack[$k1]['sum_price'];

                    // 获取产品详情
                    $wherepro['mp.lang'] =$lang;
                    $wherepro['zu.id']=$v1['pro_id'];
                    $wherepro['c.id']=$v1['prochar_id'];
                    $join = [
                        ['multi_lang mp','zu.mkey = mp.mkey','LEFT'],   // 产品名称
                        ['pro_brand b','zu.brand_id = b.id','LEFT'],
                        ['prochar c','zu.id = c.pro_id','LEFT'],   // 产品角色型号
                    ];
                    $buy_po_pack[$k1]['proinfo'] = getSearch('pro','zu',['b.name brand_name,c.model,mp.content pro_name,c.id prochar_id'],$wherepro,$join,'zu.id desc')[0];
                    $buy_po_pack[$k1]['proinfo']['img_url'] = getValue('pro_img',['pro_id'=>$v1['pro_id'],'width'=>1000],'img_url');
                    // 判断是否系统图，非系统图则取最小的。
                    if($buy_po_pack[$k1]['proinfo']['img_url'] != '/static/Admin/img/nt_logo.png'){
                        $whereUrl['pro_id'] = $v1['pro_id'];
                        $whereUrl['prochar_id'] = $v1['prochar_id'] == 0 ? 0: $v1['prochar_id'];
                        $whereUrl['width'] = 48;
                        $buy_po_pack[$k1]['proinfo']['img_url'] = Db::name('pro_img')->where($whereUrl)->group('pro_id')->value('img_url');
                    } 
                }
            }
            $buy_po[$k]['buy_po_pack'] = $buy_po_pack;
        }
        return $buy_po;
    }


    /**
     *分摊是这个金额到时候会在产品成本中体现
     *代付,是指这个金额是供应商支付,我们要转还给他
     *如果没有代付,那就不会变成应付款,只是我们自己付了款,要算成本
    **/

    function arrayWalkRecursive(&$value,$key)
    {
        switch ($key) {
            case 'content':
            case 'mkey':
                $value = base64_encode(gzcompress($value));
                break;

            case 'id':
                $len = strlen($value);
                if( $len > 3){
                    $value = substr($value,-3,3);
                }else if($len == 3){
                    $value = $value;
                }else if($len == 2){
                    $value = '0'.$value;
                }else if($len == 1){
                    $value = '00'.$value;
                }
                break;
        }

    }

}